package com.can.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.can.constant.SystemConstants;
import com.can.convert.ArticleConvert;
import com.can.domain.ResponseResult;
import com.can.domain.entity.Article;
import com.can.domain.entity.ArticleTag;
import com.can.domain.entity.Category;
import com.can.domain.vo.ArticleDetailVO;
import com.can.domain.vo.ArticleVO;
import com.can.domain.vo.HotArticleVO;
import com.can.domain.vo.PageVO;
import com.can.enums.AppHttpCodeEnum;
import com.can.exception.SystemException;
import com.can.mapper.ArticleMapper;
import com.can.service.ArticleService;
import com.can.service.ArticleTagService;
import com.can.service.CategoryService;
import com.can.util.RedisCache;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

import static com.can.constant.SystemConstants.ARTICLE_VIEWCOUNT_REDIS_PREFIX;

@Service
public class ArticleServiceImpl extends ServiceImpl<ArticleMapper, Article> implements ArticleService {

    @Lazy
    @Resource
    private CategoryService categoryService;
    @Resource
    private RedisCache redisCache;
    @Resource
    private ArticleTagService articleTagService;

    @Override
    public ResponseResult hotArticleList() {
        //查询热门文章 封装成ResponseResult返回
        LambdaQueryWrapper<Article> queryWrapper = new LambdaQueryWrapper<>();
        //必须是正式文章
        queryWrapper.eq(Article::getStatus, SystemConstants.ARTICLE_STATUS_NORMAL);
        //按照浏览量进行排序
        queryWrapper.orderByDesc(Article::getViewCount);
        //最多只查询10条
        Page<Article> page = new Page(1, 10);
        page(page, queryWrapper);

        List<HotArticleVO> vos = ArticleConvert.INSTANCE.convertList(page.getRecords());
        return ResponseResult.okResult(vos);
    }

    @Override
    public ResponseResult articleList(Integer pageNum, Integer pageSize, Long categoryId) {
        //查询条件
        LambdaQueryWrapper<Article> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        // 如果 有categoryId 就要 查询时要和传入的相同
        lambdaQueryWrapper.eq(Objects.nonNull(categoryId) && categoryId > 0, Article::getCategoryId, categoryId);
        // 状态是正式发布的
        lambdaQueryWrapper.eq(Article::getStatus, SystemConstants.ARTICLE_STATUS_NORMAL);
        // 对isTop进行降序
        lambdaQueryWrapper.orderByDesc(Article::getIsTop);

        //分页查询
        Page<Article> page = new Page<>(pageNum, pageSize);
        page(page, lambdaQueryWrapper);

        List<Article> articles = page.getRecords();
        //查询categoryName
        articles.stream()
                .forEach(article -> article.setCategoryName(categoryService.getById(article.getCategoryId()).getName()));

        //封装查询结果
        List<ArticleVO> hotArticleVOS = ArticleConvert.INSTANCE.convertList01(articles);
        PageVO pageVo = new PageVO(hotArticleVOS, page.getTotal());
        return ResponseResult.okResult(pageVo);
    }

    @Override
    public ResponseResult getArticleDetail(Long id) {
        //根据id查询文章
        Article article = getById(id);
        //从redis中获取viewCount
        Integer viewCount = redisCache.getCacheMapValue(ARTICLE_VIEWCOUNT_REDIS_PREFIX, id.toString());
        if (!ObjectUtils.isEmpty(viewCount)) {
            article.setViewCount( viewCount.longValue());
        }
        //转换成VO
        ArticleDetailVO articleDetailVO = ArticleConvert.INSTANCE.convert01(article);

        //根据分类id查询分类名
        Long categoryId = articleDetailVO.getCategoryId();
        Category category = categoryService.getById(categoryId);
        if (Objects.nonNull(category)) {
            articleDetailVO.setCategoryName(category.getName());
        }
        // 封装标签
        List<ArticleTag> articleTags = articleTagService.list(new LambdaQueryWrapper<ArticleTag>().eq(ArticleTag::getArticleId, id));
        List<Long> tagIds = articleTags.stream().map(ArticleTag::getTagId).collect(Collectors.toList());
        articleDetailVO.setTags(tagIds);
        //封装响应返回
        return ResponseResult.okResult(articleDetailVO);
    }

    @Override
    public ResponseResult updateViewCount(Long id) {
        //更新redis中对应 id的浏览量
        redisCache.incrementCacheMapValue(ARTICLE_VIEWCOUNT_REDIS_PREFIX, id.toString(), 1);
        return ResponseResult.okResult();
    }

    @Override
    @Transactional
    public ResponseResult add(ArticleVO articleVO) {
        //添加 博客
        Article article = ArticleConvert.INSTANCE.convert02(articleVO);
        save(article);

        List<ArticleTag> articleTags = articleVO.getTags().stream()
                .map(tagId -> new ArticleTag(article.getId(), tagId))
                .collect(Collectors.toList());
        //添加 博客和标签的关联
        articleTagService.saveBatch(articleTags);
        return ResponseResult.okResult();
    }

    @Override
    public PageVO page(Integer pageNum, Integer pageSize, ArticleVO articleVO) {
        Page<Article> result = new Page<>(pageNum, pageSize);
        this.page(result, new LambdaQueryWrapper<Article>()
                .like(StringUtils.hasText(articleVO.getTitle()), Article::getTitle, articleVO.getTitle())
                .like(StringUtils.hasText(articleVO.getSummary()), Article::getSummary, articleVO.getSummary())
        );
        return new PageVO(result.getRecords(), result.getTotal());
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public ResponseResult update(ArticleVO articleVO) {
        Article article = ArticleConvert.INSTANCE.convert02(articleVO);
        boolean flag = updateById(article);

        boolean flag1 = articleTagService.remove(new LambdaQueryWrapper<ArticleTag>().eq(ArticleTag::getArticleId, articleVO.getId()));
        List<ArticleTag> articleTags = articleVO.getTags().stream().map(tagId -> new ArticleTag(articleVO.getId(), tagId)).collect(Collectors.toList());
        boolean flag2 = articleTagService.saveBatch(articleTags);
        if (!flag || !flag1 || !flag2) {
            throw new SystemException(AppHttpCodeEnum.SYSTEM_ERROR);
        }
        return ResponseResult.okResult();
    }

}